<!doctype html>
<title>Many sprites</title>

<canvas width="550" height="400" style="border: 1px dashed black"></canvas>

<script src="requestAnimationFramePolyfill.js"></script>
<script>

//--- The sprite object

var spriteObject =
{
  //The x and y source position of the sprite's image
  //And its height and width
  sourceX: 0,
  sourceY: 0,
  sourceWidth: 64,
  sourceHeight: 64,
  
  //The x and y position of the sprite on the canvas
  //as well as its height
  x: 0,
  y: 0,
  width: 64,
  height: 64
};

//--- The main program

//the canvas and its drawing surface
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");

//An array to store the game sprites
var sprites = [];

//Create the background sprite, position it
//and push it into the sprites array

var background = Object.create(spriteObject);
background.sourceY = 64;
background.sourceWidth = 550;
background.sourceHeight = 400;
background.width = 550;
background.height = 400;
background.x = 0;
background.y = 0;
sprites.push(background);

//Create the cat sprite.
//Center it on the canvas and push it into the sprites array
var cat = Object.create(spriteObject);
cat.x = 0;
cat.y = 168;
sprites.push(cat);

//Create the tiger sprite, position it
//and push it into the sprites array
var tiger = Object.create(spriteObject);
tiger.sourceX = 64;
tiger.x = 300;
tiger.y = 336;
sprites.push(tiger);

//Load the cat's image 
var image = new Image();
image.addEventListener("load", loadHandler, false);
image.src = "tileSheetWithBackground.png";

function loadHandler()
{
  //Update the sprite as soon as the image has been loaded
  update();
}

function update()
{
  //Create the animation loop
  requestAnimationFrame(update, canvas);
  
  //Make the cat move right
  cat.x++;
  
  //Make the tiger move up
  tiger.y--;
  
  //Render the game
  render();
}

function render()
{ 
  //Clear the previous animation frame
  drawingSurface.clearRect(0, 0, canvas.width, canvas.height);
  
  //Loop through all the sprites and use 
  //their properties to display them
  if(sprites.length !== 0)
  {
    for(var i = 0; i < sprites.length; i++)
    {
      var sprite = sprites[i];
      drawingSurface.drawImage
      (
        image, 
        sprite.sourceX, sprite.sourceY, 
        sprite.sourceWidth, sprite.sourceHeight,
        Math.floor(sprite.x), Math.floor(sprite.y), 
        sprite.width, sprite.height
      ); 
    }
  }
}

</script>
